﻿using System;
using System.Web;
using System.Web.UI.WebControls;
using Core.Library;
using DataObject;
using DataObject.Category;
using DataObject.Product;

public partial class Controls_Product_Search : System.Web.UI.UserControl
{
    protected string Keyword;
    protected int PageIndex;
    protected int TotalRecords;

    protected void Page_Load(object sender, EventArgs e)
    {
        Keyword = Utils.GetIdFromRequestString(Utils.Keyword, string.Empty);
        PageIndex = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);

        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(Keyword))
                Keyword = HttpUtility.UrlDecode(Keyword);

            ListSearhProduct();
        }
    }

    private void ListSearhProduct()
    {
        if (!string.IsNullOrEmpty(Keyword))
        {
            var lstProduct = ProductController.Product_ListPaginationByCategory(Keyword, 0, 0, 0, PageIndex, SettingValues.PageSize_20, ref TotalRecords);

            if (lstProduct != null && lstProduct.Rows.Count > 0)
            {
                rptProduct.DataSource = lstProduct;
                rptProduct.DataBind();

                ltPager.Text = PagerUtility.PageLinks(PageIndex, SettingValues.PageSize_20, TotalRecords, SettingValues.PageStep,
                                                        UrlHelpers.ListSearchProduct(Keyword, "{0}"));

                Page.Title = string.Format(".: Tìm kiếm - {0} {1} :.", Keyword, Constants.SITE_TITLE);
            }

            ltSearch.Text = string.Format("Kết quả tìm kiếm từ khóa '{0}': {1} sản phẩm.", Keyword, TotalRecords);
        }
    }

    protected void rptProduct_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            var categoryId = ConvertUtility.ToInt32(((HiddenField)e.Item.FindControl("hfCategoryId")).Value);
            var productId = ConvertUtility.ToInt32(((HiddenField)e.Item.FindControl("hfProductId")).Value);
            var title = ((HiddenField)e.Item.FindControl("hfTitle")).Value;

            var ltTitle = (Literal)e.Item.FindControl("ltTitle");
            var ltImage = (Literal)e.Item.FindControl("ltImage");

            var categoryName = CategoryController.GetCategoryName(categoryId);

            var pHref = UrlHelpers.ProductDetail(categoryName, ConvertUtility.ToInt32(productId), title);

            var imgHref = string.Format("{0}/Thumb.ashx?Id={1}&tId={2}&Size=159&Fix=list", Constants.ThumbImage, productId, (int)CategoryType.Product);

            ltTitle.Text = string.Format("<a href=\"{0}\" class=\"title colr\">{1}</a>", pHref, UnicodeUtility.CutStrExper(title, 10));
            ltImage.Text = string.Format("<center><a href=\"{0}\" class=\"thumb\"><img src=\"{1}\" alt=\"\" /></a></center>", pHref, imgHref);
        }
    }    
}